<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视区 -->
    <el-card class="box-card">
      <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      <el-table border stripe :data="rolelist">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbtm', 'centerBox ', index1 === 0 ? 'bdtop' : '']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteTagById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 三级权限-->
              <el-col :span="19">
                <!-- for循环渲染二级权限 -->
                <el-row :class="['centerBox ', index2 === 0 ? '' : 'bdtop']" v-for="(item2, index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteTagById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- for循环渲染三级权限 -->
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="deleteTagById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifrole(scope.row.id)"> 编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleterole(scope.row.id)">删除</el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="allocationRight(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addrolrOut()">
      <el-form :model="roleForm" :rules="roleRules" ref="roleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="modifDialogVisible" width="50%" @close="modifrolrOut()">
      <el-form :model="modifroleForm" :rules="modifroleRules" ref="modifroleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifroleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifroleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightDialogVisible" width="35%" @close="rightsOut()">
      <!-- 树形控件 -->
      <el-tree :data="rightsForm" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolelist: [],
      //   添加角色对话框隐藏与显示
      addDialogVisible: false,
      //   修改角色对话框隐藏与显示
      modifDialogVisible: false,
      // 分配权限对话框隐藏与显示
      rightDialogVisible: false,
      //   添加角色
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 修改角色
      modifroleForm: {
        roleName: '',
        roleDesc: '',
        roleId: ''
      },
      modifroleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 获取所有权限
      rightsForm: [],
      // 树形属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的id值
      defKeys: [],
      // 当前即将分配权限的id值
      rightId: ''
    }
  },
  created() {
    this.addroleList()
  },
  methods: {
    async addroleList() {
      // 发送请求获取角色列表
      const { data: res } = await this.$http.get('roles')
      //   console.log(res)
      //   请求失败提醒用户
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      //   请求角色列表后渲染到页面
      this.rolelist = res.data
    },
    // 监听添加角色对话框的变化事件
    addrolrOut() {
      // resetFields()重置表单
      this.$refs.roleRef.resetFields()
    },
    // 监听修改角色对话框的变化事件
    modifrolrOut() {
      // resetFields()重置表单
      this.$refs.modifroleRef.resetFields()
    },
    addRole() {
      // 当验证通过时发送添加请求
      this.$refs.roleRef.validate(async valid => {
        const { data: res } = await this.$http.post('roles', this.roleForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        // 如果请求成功提醒用户添加成功并刷新页面
        this.addroleList()
        this.$message.success('添加成功')
        // 隐藏添加对话框
        this.addDialogVisible = false
      })
    },
    async modifrole(id) {
      // 发送获取角色信息请求
      this.modifDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      //   获取成功时将数据信息渲染到页面
      this.modifroleForm = res.data
    },
    // 修改角色
    modifRole() {
      var id = this.modifroleForm.roleId
      this.$refs.modifroleRef.validate(async valid => {
        const { data: res } = await this.$http.put('roles/' + id, this.modifroleForm)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        // 如果请求成功提醒用户修改成功并刷新页面
        this.addroleList()
        this.$message.success('修改成功')
        // 隐藏添加对话框
        this.modifDialogVisible = false
      })
    },
    // 删除角色
    async deleterole(id) {
      const deleteResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (deleteResult !== 'confirm') return this.$message.error('取消删除')
      //   如果点击确定按钮就发送删除请求
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      //   删除成功之后重新刷新页面并提醒用户删除成功
      this.addroleList()
      this.$message.success('删除成功')
    },
    // 删除权限列表
    async deleteTagById(role, rid) {
      const deleteTag = await this.$confirm('此操作将永久删除该选项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (deleteTag !== 'confirm') return this.$message.error('取消删除')
      // 如果点击确定按钮就发送删除请求
      const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rid)
      // 重新渲染权限管理列表
      role.children = res.data
      this.$message.success('删除成功')
    },
    // 获取所有权限
    async allocationRight(role) {
      this.rightId = role.id
      // 在对话框显示之前就请求获取所有权限信息数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      // 请求成功后渲染到页面
      this.rightsForm = res.data
      // 获取三级权限id值
      this.getRecursionId(role, this.defKeys)
      this.rightDialogVisible = true
    },
    // 定义一个递归函数用来获取三级权限id
    getRecursionId(node, arr) {
      /* 只有三级权限里没有children属性，所以可以进行一次判断得到三级节点
      并将三级节点里的id值添加到一个数组里 */
      if (!node.children) return arr.push(node.id)
      // 对node进行循环知道第三级节点
      node.children.forEach(item => {
        this.getRecursionId(item, arr)
      })
    },
    // 关闭分配权限对话框时重置数据信息
    rightsOut() {
      this.defKeys = []
    },
    // 提交分配权限信息
    async rightSubmit(id) {
      // 声明一个数组存储所有半选中和全选中的id
      const keysId = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const rids = keysId.join(',')
      // 发送添加权限请求
      const { data: res } = await this.$http.post(`roles/${this.rightId}/rights`, { rids: rids })

      if (res.meta.status !== 200) return this.$message.error('添加权限失败')
      // 隐藏分配权限对话框
      this.rightDialogVisible = false
      // 添加成功则重新刷新页面并提醒用户添加成功
      this.$message.success('添加权限成功')
      this.addroleList()
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  padding: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbtm {
  border-bottom: 1px solid #eee;
}
.centerBox {
  display: flex;
  align-items: center;
}
</style>
